package beego_filters

import (
	"encoding/json"
	"fmt"
	"gitee.com/yxd1990/golang-common/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"net/http"
	"strings"
)

func EnableUrlAuthFilter(exceptUrls ...string) {
	beego.InsertFilter("*", beego.BeforeRouter, func(context *context.Context) {
		if len(exceptUrls) == 0 {
			exceptUrls = append(exceptUrls, "/v1/public/**")
		}
		for _, url := range exceptUrls {
			if strings.HasSuffix(url, "**") {
				url = url[0 : len(url)-2]
				if strings.HasPrefix(context.Request.RequestURI, url) {
					return
				}
			} else if context.Request.RequestURI == url {
				return
			}
		}
		authToken := context.Request.Header.Get("Authorization")
		if authToken != "" {
			loginUserId, err := utils.LoginUtil.GetLoginUserId(authToken)
			if err == nil && loginUserId > 0 {
				return
			}
		}
		context.ResponseWriter.WriteHeader(http.StatusOK)
		retMsg := map[string]interface{}{"code": 403, "msg": "", "data": nil}
		bytes, _ := json.Marshal(retMsg)
		_, err := context.ResponseWriter.Write(bytes)
		if err != nil {
			logs.Error(fmt.Sprintf("filter response err:%v", err))
		}
	})
}
